<template>
  <el-form :inline="true" :model="searchPageData" class="demo-form-inline">
    <el-form-item label="站点名称">
      <el-input v-model="searchPageData.stationName"/>
    </el-form-item>
    <el-form-item label="状态">
      <el-select
          v-model="searchPageData.status"
          placeholder="请选择状态"
          style="width: 180px"
      >
        <el-option
            v-for="item in stationStatusList"
            :key="item.status"
            :label="item.statusName"
            :value="item.status"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getStationList">查询</el-button>
      <el-button type="primary" @click="stationReset">重置</el-button>
    </el-form-item>
  </el-form>

<!--  <div class="add-div">-->
  <div style="margin-top: 10px;margin-bottom: 10px;">
    <el-button type="primary" plain @click="addShow()">新增</el-button>
  </div>
  <!-- table -->
  <el-table :data="stationList" style="width: 90%">
    <el-table-column prop="userName" label="投资人" width="100"/>
    <el-table-column prop="stationName" label="站点名称" width="140"/>
    <el-table-column prop="address" label="详细地址" width="180"/>
    <el-table-column prop="originalPrice" label="原价" width="100"/>
    <el-table-column prop="price" label="实际价格" width="100"/>
    <el-table-column prop="dedicatedType" label="是否专用" width="100" :formatter="getDedicatedType"/>
    <el-table-column prop="status" label="状态" width="100">
      <template #default="{ row }">
      <span :class="getStatusClass(row.status)">
        {{ getStatusText(row.status) }}
      </span>
      </template>
    </el-table-column>
    <el-table-column prop="createTimeStr" label="创建时间" width="180"/>
    <el-table-column fixed="right" label="操作" width="320">
      <template #default="{ row }">
        <el-button link type="primary" size="small" @click="edit(row)">修改</el-button>
        <el-button link type="primary" size="small" @click="detail(row)">补充信息</el-button>
        <el-button link type="primary" size="small" @click="start(row)">发布</el-button>
        <el-button link :disabled="isBindButtonDisabled(row)"  type="primary" size="small" @click="setOwner(row)">绑定投资人</el-button>
        <el-button link type="primary" size="small" @click="stop(row)">停运</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div v-show="showPagination">
    <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next" :total="1000" />
  </div>
  <!-- dialog -->
  <el-dialog width="35%" :modal="station.value" v-model="dialogAddVisible">
    <el-form ref="formRef" >
      <el-form-item label="站点名称" style="width: 95%" >
        <el-input v-model="station.stationName"></el-input>
      </el-form-item>
      <el-form-item label="省市县 " >
        <el-select
            v-model="station.province"
            placeholder="请选择省"
            @change="handleChange"
            style="width: 180px"
        >
          <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
        <el-select
            v-model="station.city"
            placeholder="请选择市"
            @change="handleDistrictChange"
            style="width: 180px"
        >
          <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
        <el-select
            v-model="station.district"
            placeholder="请选择区（县）"
            style="width: 180px"
        >
          <el-option
              v-for="item in districtList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" style="width: 95%">
        <el-input v-model="station.address"></el-input>
      </el-form-item>
      <el-form-item label="是否专用">
        <el-select
            v-model="station.dedicatedType"
            placeholder="请选择专用类型"
            style="width: 180px"
        >
          <el-option
              v-for="item in specialTypes"
              :key="item.id"
              :label="item.specialTypeName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="原价 "  style="width: 95%">
        <el-input v-model="station.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="实际价格" style="width: 95%">
        <el-input v-model="station.price"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitAdd">提交</el-button>
        <el-button type="primary" @click="closeAdd()">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!-- dialog -->
  <el-dialog width="40%" :modal="station.value" v-model="dialogEditVisible">
    <el-form ref="formRef" label-width="100px">
      <el-form-item label="站点名称">
        <el-input v-model="station.stationName"></el-input>
      </el-form-item>
      <el-form-item label="充电站地址">
        <el-input v-model="station.address"></el-input>
      </el-form-item>
      <el-form-item label="是否专用">
        <el-select
            v-model="station.dedicatedType"
            placeholder="请选择专用类型"
            style="width: 180px"
        >
          <el-option
              v-for="item in specialTypes"
              :key="item.id"
              :label="item.specialTypeName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="原价">
        <el-input v-model="station.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="实际价格">
        <el-input v-model="station.price"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitEdit">提交</el-button>
        <el-button type="primary" @click="closeEdit()">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog width="40%" :modal="station.value" v-model="dialogDetailVisible">
    <el-form ref="formRef" label-width="100px">
      <!--        <el-form-item label="投资人">-->
      <!--          <el-input v-model="station.userName"></el-input>-->
      <!--        </el-form-item>-->
      <el-form-item label="站点名称">
        <el-input v-model="station.stationName" readonly></el-input>
      </el-form-item>

      <el-form-item label="停车费">
        <el-input v-model="station.parkFee"></el-input>
      </el-form-item>
      <el-form-item label="是否有休息室">
        <el-select
            v-model="station.lounge"
            placeholder=""
            style="width: 180px"
        >
          <el-option
              v-for="item in flagDescList"
              :key="item.id"
              :label="item.desc"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有厕所">
        <el-select
            v-model="station.toilet"
            placeholder=""
            style="width: 180px"
        >
          <el-option
              v-for="item in flagDescList"
              :key="item.id"
              :label="item.desc"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有购物中心">
        <el-select
            v-model="station.shoppingMall"
            placeholder=""
            style="width: 180px"
        >
          <el-option
              v-for="item in flagDescList"
              :key="item.id"
              :label="item.desc"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否能洗车">
        <el-select
            v-model="station.washCar"
            placeholder=""
            style="width: 180px"
        >
          <el-option
              v-for="item in flagDescList"
              :key="item.id"
              :label="item.desc"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="洗车费">
        <el-input v-model="station.washFee"></el-input>
      </el-form-item>
      <el-form-item label="经营开始时间">
        <el-input v-model="station.businessStartTime"></el-input>
      </el-form-item>
      <el-form-item label="经营结束时间">
        <el-input v-model="station.businessEndTime"></el-input>
      </el-form-item>
      <el-form-item label="是否有餐厅">
        <el-select
            v-model="station.diet"
            placeholder=""
            style="width: 180px"
        >
          <el-option
              v-for="item in flagDescList"
              :key="item.id"
              :label="item.desc"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经度">
        <el-input v-model="station.longitude"></el-input>
      </el-form-item>
      <el-form-item label="纬度">
        <el-input v-model="station.latitude"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitDetailAdd">提交</el-button>
        <el-button type="primary" @click="closeDetailEdit()">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog width="28%" :modal="user.value" v-model="dialogSetOwnerVisible">
    <div class="my-header">
      <h4>站点名称： {{ stationName }}</h4>
    </div>
    <el-form :inline="true" :model="userSearch" class="demo-form-inline">
      <el-form-item label="手机号" placeholder="请输入手机号">
        <el-input v-model="userSearch.phone"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList">查询</el-button>
        <el-button type="primary" @click="userReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="userList" style="width: 90%">
      <el-table-column prop="nickName" label="投资人姓名" width="100"/>
      <el-table-column prop="phone" label="联系电话" width="120"/>
      <el-table-column prop="authentication" label="状态" width="100">
        <template #default="{ row }">
      <span :class="getStatusClass(row.authentication)">
        {{ getUserStatusText(row.authentication) }}
      </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="60">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="bind(row)">绑定</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>
<script setup>
import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  StationList,
  StationAdd,
  StationEdit,
  StationBind,
  StationStop,
  StationStart,
  StationDetailEdit
} from '@/api/station/station.js'
import {AreaCityList, ProvinceCityList, UserInfoList} from "@/api/user/userinfo.js";
//table部分
//定义一个数据模型
const station = ref({
  id: '',
  userId: '',
  userName: '',
  stationName: '',
  province: '',
  city: '',
  district: '',
  address: '',
  status: '',
  createTime: '',
  dedicatedType: '',
  chargingSpeedType: '',
  originalPrice: '',
  price: '',
  parkFee: '',
  lounge: '',
  toilet: '',
  shoppingMall: '',
  washCar: '',
  washFee: '',
  businessStartTime: '',
  businessEndTime: '',
  diet: '',
  longitude: '',
  latitude: ''
});
// 定义一个list用来接收后端返回的数据列表
const stationList = ref([]);
//定义一个标识---是否需要展示dialog
const dialogDetailVisible = ref(false);
const dialogEditVisible = ref(false);
const dialogAddVisible = ref(false);
const dialogSetOwnerVisible = ref(false);
const showPagination = ref(false);

const searchPageData = ref({
  stationName: '',
  status: '',
  pageSize: 10,
  currentPage: 1
})

const stationId = ref(null);
const stationName = ref('');

const provinceList = ref([])

const cityList=ref([]);

const districtList=ref([]);

const areaCode = ref('');

getProvinceCityList();
function getProvinceCityList() {
  console.info("get province city list");
  ProvinceCityList().then(res => {
    console.info(res.data)
    if (res.data.code === 200000) {
      provinceList.value = res.data.data;
    }
  } ).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });
}

function handleChange(newVal) {
  console.info(newVal)
  AreaCityList(newVal).then(res => {
    console.info(res.data)
    if (res.data.code === 200000) {
      cityList.value = res.data.data;
      if (res.data.data.length > 0) {
        if( res.data.data[0].areaCode ===  res.data.data[0].parentCode){
          districtList.value = res.data.data;
          cityShow.value = false;
        }
      }
    }
  } ).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });

}
function handleDistrictChange(newVal) {
  console.info(newVal)
  AreaCityList(newVal).then(res => {
    console.info(res.data)
    if (res.data.code === 200000) {
      districtList.value = res.data.data;
    }
  } ).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });

}


//定义投资人数据模型
const user = ref({
  userId: '',
  userName: '',
  nickName: '',
  phone: '',
  status: '',
  createTime: ''
});
const userSearch = ref({
  pageSize: 10,
  phone: '',
  currentPage: 1,
});

// 定义一个list用来接收后端返回的数据列表
const userList = ref([]);


function userReset() {
  userSearch.value.phone = '';
}

function getUserList() {
  console.info("get user list");
  UserInfoList(userSearch.value).then(res => {
    console.info(res.data)
    if (res.data.code === 200000) {
      userList.value = res.data.data.data;
    } else {
      console.info(res.data.msg);
    }
  }).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });
}

function bind(data) {
  const userName = data.nickName;
  station.value.userName = userName;
  station.value.userId = data.id;
  station.value.id = stationId.value;
  ElMessageBox.confirm(
      `是否确认绑定：${userName} 为当前充电站的投资人`,
      '提醒', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    StationBind(station.value)
        .then(res => {
          if (res.data.code === 200000) {
            closeBind();
            ElMessage({
              message: `${data.userName} 已绑定成功`,
              type: 'success'
            });
            getStationList();
          } else {
            //错误提示框
            ElMessage({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '绑定取消'
    })
  })
}


function closeBind() {
  dialogSetOwnerVisible.value = false;
  //清空表单数据
  stationId.value = null;
  stationName.value = '';
  Object.keys(user.value).forEach(key => {
    user.value[key] = '';
  });
}


getStationList();

function stationReset() {
  searchPageData.value.stationName = '';
  searchPageData.value.status = '';
}

function getStationList() {
  StationList(searchPageData.value).then(res => {
    console.info(res.data)
    if (res.data.code === 200000) {
      stationList.value = res.data.data.data;
    } else {
      console.info(res.data.msg);
    }
  })
}

const onSubmitAdd = () => {
  StationAdd(station.value)
      .then(res => {
        if (res.data.code == 200000) {
          closeAdd();
          getStationList();
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      }).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });
}

function onSubmitDetailAdd(){
  StationDetailEdit(station.value)
      .then(res => {
        if (res.data.code === 200000) {
          closeDetailEdit();
          getStationList();
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      }).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });
}
const onSubmitEdit = () => {
  StationEdit(station.value)
      .then(res => {
        if (res.data.code === 200000) {
          closeEdit();
          getStationList();
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      }).catch(() => {
    //错误提示框
    ElMessage({
      message: '请求失败，请稍后再试',
      type: 'warning'
    });
  });
}

function detail(data) {
  dialogDetailVisible.value = true;
  station.value = {...data};
}

function start(data) {
  ElMessageBox.confirm(
      '是否确认发布',
      '提醒', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    StationStart(data)
        .then(res => {
          if (res.data.code === 200000) {
            ElMessage({
              message: '发布成功',
              type: 'success'
            });
            getStationList();
          } else {
            //错误提示框
            ElMessage({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '停运取消'
    })
  })
}

// 详情

function Detail(data) {
  station.value = {...data};
  dialogDetailVisible.value = true;
}

function DetailClose() {
  dialogDetailVisible.value = false;
}


function edit(data) {
  dialogEditVisible.value = true;
  station.value = {...data};
}

function setOwner(data) {
  dialogSetOwnerVisible.value = true;
  stationId.value = data.id;
  stationName.value = data.stationName;
  getUserList();
}

function stop(data) {
  ElMessageBox.confirm(
      '是否确认停运',
      '提醒', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    StationStop(data)
        .then(res => {
          if (res.data.code === 200000) {
            ElMessage({
              message: '停运成功',
              type: 'success'
            });
            getStationList();
          } else {
            //错误提示框
            ElMessage({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '停运取消'
    })
  })
}

function closeAdd() {
  dialogAddVisible.value = false;
  //清空表单数据
  Object.keys(station.value).forEach(key => {
    station.value[key] = '';
  });
}

function closeEdit() {
  dialogEditVisible.value = false;
  //清空表单数据
  Object.keys(station.value).forEach(key => {
    station.value[key] = '';
  });
}
function closeDetailEdit() {
  dialogDetailVisible.value = false;
  //清空表单数据
  Object.keys(station.value).forEach(key => {
    station.value[key] = '';
  });
}
function addShow() {
  dialogAddVisible.value = true;
}

function getStatusClass(status) {
  switch (status) {
    case 0:
      return 'text-forestgreen'
    case 1:
      return 'text-green'
    case 2:
      return 'text-red'
    case 3:
      return 'text-black'
    default:
      return ''
  }
}

function getDedicatedType(row, column, cellValue) {
  switch (cellValue) {
    case 0:
      return '否'
    case 1:
      return '是'
    default:
      return ''
  }
}

function getStatusText(status) {
  switch (status) {
    case 0:
      return '建设中'
    case 1:
      return '运营中'
    case 2:
      return '停运'
    case 3:
      return '维修中'
    default:
      return ''
  }
}

const stationStatusList = ref([
  {
    status: 0,
    statusName: '建设中'
  },
  {
    status: 1,
    statusName: '运营中'
  },
  {
    status: 2,
    statusName: '停运'
  },
  {
    status: 3,
    statusName: '维修中'
  }
]);

function getUserStatusText(status) {
  switch (status) {
    case 0:
      return '待上传'
    case 1:
      return '待认证'
    case 2:
      return '已认证'
    case 3:
      return '认证失败'
    default:
      return ''
  }
}
const flagDescList = ref([
  {
    id: 0,
    desc: '无'
  },
  {
    id: 1,
    desc: '有'
  }
]);
function isBindButtonDisabled(row) {
  return !(row.userId === null);
}
const specialTypes = ref([
  {
    id: 0,
    specialTypeName: '否'
  },
  {
    id: 1,
    specialTypeName: '是'
  }
]);
</script>

<style>
.text-forestgreen {
  color: forestgreen;
}

.text-green {
  color: blue;
}

.text-red {
  color: red;
}

.text-black {
  color: black;
}
.my-header {
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  justify-content: space-between;
  gap: 16px;
}
</style>